package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * Semaphore 可以在并发状态下维护当前访问自身的线程个数，其它线程处于waitting状态
 * 使用Semaphore可以控制同时访问资源的线程个数。例如，实现一个文件允许的并发访问数
 *
 * @Author: robert.song
 * @Date: Created in 2021/11/27
 */
@Slf4j(topic = "Semaphore")
public class Thread_14_1_Semaphore {
    public static void main(String[] args) throws InterruptedException {
//        创建Semaphore对象
        Semaphore semaphore = new Semaphore(3);
//        10个线程同时运行
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(() -> {
                try {
                    semaphore.acquire();
                    Thread.sleep(10000);
                    log.info("running...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    log.info("end...");
                    semaphore.release();
                }
            }, "thread_" + i);
            t.start();
            Thread.sleep(1000);
            log.info("thread_" + i + " {}", t.getState());
        }
    }
}
